import glob
import pprint
from ConfigParser import RawConfigParser

from clutch import C, G, Controller, expose, ContinueTraversal
from clutch.command import available_instances, load_mtab, save_mtab

from clutch.admin.topes import config_model, config_dict

class Root(Controller):

    @expose('index.html')
    def index(self):
        mtab = load_mtab()
        mtab = sorted(mtab.items(), key=lambda (k,v):(len(k),k))
        instances = sorted(available_instances())
        return dict(mtab=mtab, instances=instances)

    def _on_404(self, inst, *args, **kwargs):
        raise ContinueTraversal(InstanceAdmin(inst), args)

class InstanceAdmin(Controller):

    def __init__(self, instance):
        self.instance = instance
        self.config_file = 'apps/%s.ini' % instance

    @expose('instance.html')
    def index(self):
        model = config_model(self.config)
        value = config_dict(self.config)
        C.topeviews.config = model.default_view()
        return dict(name=self.instance, value=value)

    def _get_config(self):
        cp = RawConfigParser()
        cp.read(self.config_file)
        return cp
    def _set_config(self, cp):
        cp.write(open(self.config_file, 'wb'))
    config = property(_get_config, _set_config)
    


        
